﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace GurLoader.View
{
    public class AutoElipseTextConverter : BaseConverter, IValueConverter
    {
        private const int MaxCharacters = 40;

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
                return string.Empty;

            string text = value.ToString();

            if (string.IsNullOrEmpty(text))
                return string.Empty;

            // we will take the file name + extension plus as many characters on the left as possible before ellipsing
            if (text.Length <= 40)
                return text;

            string filename = Path.GetFileName(text);

            // shorten excessively long filenames. Assume there needs to be at LEAST
            // 5 chars for the start of the path, plus the 4 delim ( elipsed )
            // characters
            bool isTruncFilename = false;
            if (filename.Length > (40 - (4 + 5)))
            {
                filename = filename.Substring( filename.Length - (40 - (4 + 5)));
                isTruncFilename = true;
            }

            string left = text.Substring(0, 40 - (filename.Length + 4));
            string pathSepString = Path.DirectorySeparatorChar.ToString();
            if (left.EndsWith(pathSepString))
                left = left.Substring(0, left.Length - pathSepString.Length);

            if ( isTruncFilename )
                return string.Format("{0}...{1}", left, filename);
            else
                return string.Format("{0}...{1}{2}", left, Path.DirectorySeparatorChar ,filename);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
